//
//  RegexHelper.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/25.
//

import Foundation

/// 正则校验工具
public class RegexHelper {
    public static let share = RegexHelper()

    var regex: NSRegularExpression?

    /// 电话号码
    let phonePattern = "^1(3[0-9]|4[579]|5[0-35-9]|6[6]|7[0-35-9]|8[0-9]|9[89])\\d{8}$"
    /// 邮箱
    let mailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    /// 密码6-18位字母数字
    let pwdPattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}"

    private func match(input: String) -> Bool {
        guard regex != nil else {
            return false
        }

        let matches = regex!.matches(in: input,
                                     options: [],
                                     range: NSRange(location: 0, length: input.utf16.count))
        return !matches.isEmpty
    }

    
    /// 校验手机号码
    /// - Parameter phone: 号码
    /// - Returns: 返回值
    public func matchPhone( phone: String ) -> Bool {
        try? regex = NSRegularExpression(pattern: phonePattern, options: .caseInsensitive)
        return match(input: phone)
    }
    
    /// 校验邮箱
    /// - Parameter email: 邮箱
    /// - Returns: 返回值
    public func matchEmail( email: String ) -> Bool {
        try? regex = NSRegularExpression(pattern: phonePattern, options: .caseInsensitive)
        return match(input: email)
    }

    /// 匹配字母和数字
    public func matchLetterAndNumber(str: String) -> Bool {
        try? regex = NSRegularExpression(pattern: "^[A-Za-z0-9]+$", options: .caseInsensitive)
        return match(input: str)
    }

    
    /// 校验密码
    /// - Parameter name: 密码
    /// - Returns: 返回值
    public func matchPwd(name: String) -> Bool {
        try? regex = NSRegularExpression(pattern: pwdPattern, options: .caseInsensitive)
        return match(input: name)
    }
}
